package com.kun.authServer.controller;


import com.kun.authServer.feign.AdminFeignService;
import com.kun.authServer.utils.ValidateCodeUtil;
import com.kun.authServer.vo.AdminVo;
import com.kun.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.soap.SAAJResult;

@Slf4j
@RestController
@RequestMapping("auth")
public class CodeController {
    @Autowired
    AdminFeignService adminFeignService;
    // 生成验证码,返回的是 base64
    @GetMapping("/getCaptchaBase64")
    public R getCaptchaBase64(HttpServletRequest request, HttpServletResponse response) {


        try {

            response.setContentType("image/png");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Expire", "0");
            response.setHeader("Pragma", "no-cache");
            ValidateCodeUtil validateCode = new ValidateCodeUtil();
            // 返回base64
            String base64String = validateCode.getRandomCodeBase64(request, response);


            //http://tool.chinaz.com/tools/imgtobase/  base64直接转为图片网站
            return R.ok().put("url","data:image/png;base64," + base64String);
        } catch (Exception e) {
            System.out.println(e);
        }

        return R.error();
    }
    //验证码校验
    @GetMapping("/checkCaptcha")
    public R getCheckCaptcha(@RequestParam("code") String code,
                             @RequestParam("memberName") String memberName,
                             @RequestParam("memberPass") String memberPass,
                             HttpSession session ) {
        AdminVo adminVo = new AdminVo();
        adminVo.setMemberName(memberName);
        adminVo.setMemberPass(memberPass);
        try {
            //toLowerCase() 不区分大小写进行验证码校验
            String sessionCode= String.valueOf(session.getAttribute("JCCODE")).toLowerCase();
            System.out.println("session里的验证码："+sessionCode);
            String receivedCode=code.toLowerCase();
            System.out.println("用户的验证码："+receivedCode);
            if (!sessionCode.equals("") && !receivedCode.equals("") && sessionCode.equals(receivedCode)){
                R login = adminFeignService.login(adminVo);
                if (login.getCode()==0){
                    return R.ok().put("token",login.get("token"));
                }else {
                    return R.error().put("msg","用户名密码错误");
                }
            }

        } catch (Exception e) {

            System.out.println(e);
        }
        return R.error().put("msg","验证码错误");
    }

}